import config from "./config";
const COS = require("../libs/cos-wx-sdk-v5");

const cos = new COS({
  SecretId: 'AKIDQmxHUaKWF9vFSWtBmBOwMadVBf1CfyY1',
  SecretKey: 'SjpjS3Vn7GDyXu53rX3NXWKyQhmhT5Vj',
});

const http = {
    post(service, params) {
      return new Promise((resolve, reject) => {
        wxRequest('POST', resolve, reject, service, params);
      });
    },
    upload(count) {
      return new Promise((resolve, reject) =>{
        wx.chooseImage({
          count: count? count: 1, // 默认9
          sizeType: ['original'], // 可以指定是原图还是压缩图，默认用原图
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
              let filePath = res.tempFiles[0].path;
              let filename = filePath.substr(filePath.lastIndexOf('/') + 1);
              cos.postObject({
                  Bucket: 'menjin-1251461298',
                  Region: 'ap-chengdu',
                  Key: 'weixin/' + filename,
                  FilePath: filePath,
                  onProgress: function (info) {
                    // console.log(JSON.stringify(info));
                  }
              }, function (err, data) {
                if(err) {
                  reject(err)
                }else{
                  resolve("https://" +data.Location);
                }
              });
          }
        });
      })
    }
  };
  
function wxRequest(type, resolve, reject, service, params) {
  let userInfo = wx.getStorageSync("userInfo");
  if(userInfo) {
    console.log(userInfo)
    let _userInfo = JSON.parse(userInfo) || {};
    params.openid = _userInfo.openid;
    params.userid = _userInfo.userid;
  }
    wx.request({
        method: type,
        url: service,
        ...config,
        data: params,
        success: function(res) {
          console.log(res);
          if(res.data.code === 200) {
            resolve(res.data.body);
          } else if(res.data.code === 500) {
            reject(res.data)
          }
        },
        fail: function(err) {
          reject(err.data);
        }
    });
}
  
export default http;